package com.ken.mqbase.message;

import com.ken.constant.RabbitConstant;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * 使用原jar包，一个设置message的测试列子（消费者）
 * Created by renchongyu on 2018/11/12.
 */
public class ProducerMessage {

    public static void main(String[] args) throws Exception{

        //1.创建一个ConnectionFactory
        ConnectionFactory conn = new ConnectionFactory();
        conn.setHost(RabbitConstant.RABBITMQ_IP);
        conn.setPort(RabbitConstant.RABBITMQ_PORT);
        conn.setUsername(RabbitConstant.RABBITMQ_USER_NAME);
        conn.setPassword(RabbitConstant.RABBITMQ_USER_PASSWORD);
        conn.setVirtualHost(RabbitConstant.RABBITMQ_VIRTUAL_HOST);

        //2.通过连接工厂连接
        Connection connection = conn.newConnection();

        //3.通过连接创建一个channel
        Channel channel = connection.createChannel();
        //3.1延伸的配置文件，有来自定义设置
        Map<String,Object> headers = new HashMap<>();
        headers.put("name","Ken");
        headers.put("study","English");
        //注意写法，一定要这样写,否则自定义配置无效
        AMQP.BasicProperties properties = new AMQP.BasicProperties()
        .builder()
        .deliveryMode(2)//投递模式：2持久化
        .contentEncoding("utf-8")//编码字符集
        .expiration("10000")//消息在队列里存储的时间
        .headers(headers)//可以理解为头信息
        .build();

        //4.通过channel发送一条消息
        String msg = "Hello RabbitMQ! from Ken's to Message test";
        /**
         * exchange路由器
         * routingKey key键
         * props 配置
         * body 实际消息
         */
        for(int i=0;i<5;i++){
            channel.basicPublish("","test001",properties,msg.getBytes());
        }

        //5.关闭相关连接
        channel.close();
        connection.close();

    }
}
